import 'dart:io';
import 'package:photo_manager/photo_manager.dart';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:path_provider/path_provider.dart';
import '../model/apiResponse.dart';
import 'base/apiClient.dart';

class UploadService {
  final ApiClient _apiClient = ApiClient();

  // 从视频提取第一帧作为缩略图
  Future<File?> extractVideoThumbnail(AssetEntity videoAsset) async {
    try {
      print('=== 开始提取视频缩略图 ===');
      print('视频Asset ID: ${videoAsset.id}');

      // 获取视频文件
      final File? videoFile = await videoAsset.file;
      if (videoFile == null) {
        throw Exception('无法获取视频文件');
      }

      print('视频文件路径: ${videoFile.path}');

      // 获取临时目录
      final Directory tempDir = await getTemporaryDirectory();

      // 使用简单的时间戳作为文件名，避免特殊字符问题
      final String thumbnailPath =
          '${tempDir.path}/video_thumbnail_${DateTime.now().millisecondsSinceEpoch}.jpg';

      print('缩略图保存路径: $thumbnailPath');

      // 提取视频第一帧
      final String? thumbnailFilePath = await VideoThumbnail.thumbnailFile(
        video: videoFile.path,
        thumbnailPath: thumbnailPath,
        imageFormat: ImageFormat.JPEG,
        maxHeight: 1080, // 设置最大高度
        quality: 25, // 设置质量
        timeMs: 0, // 提取第一帧（0毫秒）
      );

      if (thumbnailFilePath != null) {
        final File thumbnailFile = File(thumbnailFilePath);
        if (await thumbnailFile.exists()) {
          print('✅ 视频缩略图提取成功');
          print('缩略图文件大小: ${await thumbnailFile.length()} bytes');
          return thumbnailFile;
        }
      }

      throw Exception('视频缩略图提取失败');
    } catch (e) {
      print('=== 视频缩略图提取失败 ===');
      print('Error: $e');
      print('========================');
      return null;
    }
  }

  // 添加分组上传方法
  Future<List<String>> uploadImagesInBatches(List<AssetEntity> imageAssets,
      {int batchSize = 2}) async {
    if (imageAssets.isEmpty) return [];

    final Stopwatch totalStopwatch = Stopwatch()..start();
    List<String> allUploadedUrls = [];

    try {
      print('=== 开始分组上传图片 ===');
      print('总图片数量: ${imageAssets.length}');
      print('每组数量: $batchSize');
      print('总组数: ${(imageAssets.length / batchSize).ceil()}');
      print('开始时间: ${DateTime.now()}');

      // 分组上传
      for (int i = 0; i < imageAssets.length; i += batchSize) {
        int end = (i + batchSize < imageAssets.length)
            ? i + batchSize
            : imageAssets.length;
        List<AssetEntity> batch = imageAssets.sublist(i, end);
        int batchNumber = (i ~/ batchSize) + 1;
        int totalBatches = (imageAssets.length / batchSize).ceil();

        print(
            '\n--- 开始上传第${batchNumber}/${totalBatches}组 (${batch.length}张图片) ---');

        final Stopwatch batchStopwatch = Stopwatch()..start();

        try {
          List<String> batchUrls = await _uploadSingleBatch(batch, batchNumber);
          allUploadedUrls.addAll(batchUrls);
          batchStopwatch.stop();

          print(
              '✅ 第${batchNumber}组上传成功 (耗时: ${batchStopwatch.elapsedMilliseconds}ms)');
          print('本组获得URLs: $batchUrls');
          print('已完成: ${allUploadedUrls.length}/${imageAssets.length}张图片');

          // 组间稍作延迟，避免服务器压力
          if (i + batchSize < imageAssets.length) {
            print('等待1秒后继续下一组...');
            await Future.delayed(Duration(seconds: 1));
          }
        } catch (e) {
          batchStopwatch.stop();
          print(
              '❌ 第${batchNumber}组上传失败 (耗时: ${batchStopwatch.elapsedMilliseconds}ms): $e');
          throw Exception('第${batchNumber}组上传失败: $e');
        }
      }

      totalStopwatch.stop();

      print('\n=== 分组上传完成 ===');
      print(
          '总耗时: ${totalStopwatch.elapsedMilliseconds}ms (${(totalStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
      print(
          '平均每张图片耗时: ${(totalStopwatch.elapsedMilliseconds / imageAssets.length).toStringAsFixed(2)}ms');
      print('成功上传${allUploadedUrls.length}张图片');
      print('所有URLs: $allUploadedUrls');
      print('=====================');

      return allUploadedUrls;
    } catch (e) {
      totalStopwatch.stop();
      print('\n=== 分组上传失败 ===');
      print('Error: $e');
      print('失败前总耗时: ${totalStopwatch.elapsedMilliseconds}ms');
      print('已成功上传: ${allUploadedUrls.length}张图片');
      print('==================');
      throw Exception('分组上传图片失败: $e');
    }
  }

  // 上传单个批次的图片
  Future<List<String>> _uploadSingleBatch(
      List<AssetEntity> batch, int batchNumber) async {
    final Stopwatch batchStopwatch = Stopwatch()..start();

    try {
      print('构建第${batchNumber}组FormData...');
      final Stopwatch formDataStopwatch = Stopwatch()..start();

      FormData formData = FormData();
      formData.fields.add(MapEntry('type', '5')); // 图片类型为5

      // 为每个文件添加单独的files字段
      for (int i = 0; i < batch.length; i++) {
        AssetEntity asset = batch[i];

        print('  处理第${i + 1}/${batch.length}张图片: ${asset.id}');

        final File? file = await asset.file;
        if (file != null && await file.exists()) {
          final int fileSize = await file.length();
          print('    文件大小: ${(fileSize / 1024 / 1024).toStringAsFixed(2)} MB');

          String fileName = _generateFileName(asset, file);
          MediaType? contentType = _getContentType(fileName);

          MultipartFile multipartFile = await MultipartFile.fromFile(
            file.path,
            filename: fileName,
            contentType: contentType,
          );

          formData.files.add(MapEntry('files', multipartFile));
          print('    ✅ 已添加到FormData');
        } else {
          throw Exception('无法获取文件: ${asset.id}');
        }
      }

      formDataStopwatch.stop();
      print('FormData构建完成 (耗时: ${formDataStopwatch.elapsedMilliseconds}ms)');

      if (formData.files.isEmpty) {
        throw Exception('第${batchNumber}组没有可上传的文件');
      }

      // 网络上传
      final Stopwatch networkStopwatch = Stopwatch()..start();
      print('开始网络上传第${batchNumber}组...');

      String uri = '/api/v1/bgc/file/uploadMore';
      final response = await _apiClient.post(
        uri,
        data: formData,
        headers: {'Accept': '*/*'},
        onSendProgress: (sent, total) {
          double progress = sent / total;
          double speedMBps = (sent / 1024 / 1024) /
              (networkStopwatch.elapsedMilliseconds / 1000);
          if (networkStopwatch.elapsedMilliseconds > 0) {
            print(
                '    📤 第${batchNumber}组进度: ${(progress * 100).toStringAsFixed(1)}% '
                '速度: ${speedMBps.toStringAsFixed(2)} MB/s');
          }
        },
      );

      networkStopwatch.stop();
      print(
          '第${batchNumber}组网络上传完成 (耗时: ${networkStopwatch.elapsedMilliseconds}ms)');

      // 解析响应
      final Stopwatch parseStopwatch = Stopwatch()..start();
      List<String> result = _parseUploadResponse(response.data);
      parseStopwatch.stop();

      batchStopwatch.stop();

      print('第${batchNumber}组时间统计:');
      print('  - FormData构建: ${formDataStopwatch.elapsedMilliseconds}ms');
      print('  - 网络上传: ${networkStopwatch.elapsedMilliseconds}ms');
      print('  - 响应解析: ${parseStopwatch.elapsedMilliseconds}ms');
      print('  - 总耗时: ${batchStopwatch.elapsedMilliseconds}ms');

      return result;
    } catch (e) {
      batchStopwatch.stop();
      print(
          '第${batchNumber}组上传失败 (耗时: ${batchStopwatch.elapsedMilliseconds}ms): $e');
      rethrow;
    }
  }

  // 修改原有的 uploadImages 方法，自动选择上传策略
  Future<List<String>> uploadImages(List<AssetEntity> imageAssets) async {
    if (imageAssets.isEmpty) return [];

    // 如果图片数量大于2张，使用分组上传
    if (imageAssets.length > 2) {
      print('图片数量(${imageAssets.length})超过2张，使用分组上传策略');
      return await uploadImagesInBatches(imageAssets, batchSize: 2);
    } else {
      print('图片数量(${imageAssets.length})较少，使用单次上传策略');
      return await _uploadImagesOriginal(imageAssets);
    }
  }

  // 重命名原有的上传方法
  Future<List<String>> _uploadImagesOriginal(
      List<AssetEntity> imageAssets) async {
    if (imageAssets.isEmpty) return [];

    final Stopwatch totalStopwatch = Stopwatch()..start();

    try {
      print('=== 开始单次上传图片 ===');
      print('待上传图片数量: ${imageAssets.length}');
      print('开始时间: ${DateTime.now()}');

      final Stopwatch formDataStopwatch = Stopwatch()..start();

      FormData formData = FormData();
      formData.fields.add(MapEntry('type', '5')); // 图片类型为5

      // 为每个文件添加单独的files字段
      for (int i = 0; i < imageAssets.length; i++) {
        AssetEntity asset = imageAssets[i];
        final Stopwatch assetStopwatch = Stopwatch()..start();

        print('--- 处理第${i + 1}/${imageAssets.length}张图片 ---');
        print('Asset ID: ${asset.id}');
        print('Asset Type: ${asset.type}');
        print('Asset Title: ${asset.title}');

        // 获取文件时间统计
        final Stopwatch fileStopwatch = Stopwatch()..start();
        final File? file = await asset.file;
        fileStopwatch.stop();

        if (file != null) {
          print('✅ 成功获取文件 (耗时: ${fileStopwatch.elapsedMilliseconds}ms)');
          print('文件路径: ${file.path}');
          print('文件是否存在: ${await file.exists()}');

          if (await file.exists()) {
            final int fileSize = await file.length();
            print(
                '文件大小: $fileSize bytes (${(fileSize / 1024 / 1024).toStringAsFixed(2)} MB)');
          }

          // 生成文件名时间统计
          final Stopwatch nameStopwatch = Stopwatch()..start();
          String fileName = _generateFileName(asset, file);
          nameStopwatch.stop();
          print(
              '生成的文件名: $fileName (耗时: ${nameStopwatch.elapsedMilliseconds}ms)');

          // 根据文件扩展名确定ContentType
          MediaType? contentType = _getContentType(fileName);
          print('文件类型: $contentType');

          // 创建MultipartFile时间统计
          final Stopwatch multipartStopwatch = Stopwatch()..start();
          MultipartFile multipartFile = await MultipartFile.fromFile(
            file.path,
            filename: fileName,
            contentType: contentType,
          );
          multipartStopwatch.stop();

          print(
              'MultipartFile 创建成功 (耗时: ${multipartStopwatch.elapsedMilliseconds}ms)');
          print('MultipartFile 文件名: ${multipartFile.filename}');
          print('MultipartFile 长度: ${multipartFile.length}');

          // 每个文件都添加一个独立的files字段（这是关键！）
          formData.files.add(MapEntry('files', multipartFile));
          print('已添加到FormData，当前files数量: ${formData.files.length}');
        } else {
          print('❌ 无法获取文件: asset.file 返回null');
        }

        assetStopwatch.stop();
        print(
            '--- 第${i + 1}张图片处理完成 (总耗时: ${assetStopwatch.elapsedMilliseconds}ms) ---\n');
      }

      formDataStopwatch.stop();
      print('FormData 构建完成 (总耗时: ${formDataStopwatch.elapsedMilliseconds}ms)');

      if (formData.files.isEmpty) {
        throw Exception('没有可上传的文件');
      }

      print('FormData 结构: type=5, files字段数量=${formData.files.length}');

      // 网络上传时间统计
      final Stopwatch networkStopwatch = Stopwatch()..start();
      print('开始网络上传...');
      print('上传开始时间: ${DateTime.now()}');

      String uri = '/api/v1/bgc/file/uploadMore';
      final response = await _apiClient.post(
        uri,
        data: formData,
        headers: {'Accept': '*/*'},
        onSendProgress: (sent, total) {
          double progress = sent / total;
          double speedMBps = (sent / 1024 / 1024) /
              (networkStopwatch.elapsedMilliseconds / 1000);
          print('📤 上传进度: ${(progress * 100).toStringAsFixed(1)}% '
              '($sent/$total bytes) '
              '速度: ${speedMBps.toStringAsFixed(2)} MB/s '
              '已用时: ${networkStopwatch.elapsedMilliseconds}ms');
        },
      );

      networkStopwatch.stop();
      print('网络上传完成 (耗时: ${networkStopwatch.elapsedMilliseconds}ms)');
      print('上传结束时间: ${DateTime.now()}');

      // 响应解析时间统计
      final Stopwatch parseStopwatch = Stopwatch()..start();

      print('=== 上传响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${response.data}');
      print('=================');

      // 解析响应
      List<String> result = _parseUploadResponse(response.data);
      parseStopwatch.stop();

      totalStopwatch.stop();

      print('=== 上传时间统计汇总 ===');
      print('FormData构建时间: ${formDataStopwatch.elapsedMilliseconds}ms');
      print('网络上传时间: ${networkStopwatch.elapsedMilliseconds}ms');
      print('响应解析时间: ${parseStopwatch.elapsedMilliseconds}ms');
      print(
          '总耗时: ${totalStopwatch.elapsedMilliseconds}ms (${(totalStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
      print(
          '平均每张图片耗时: ${(totalStopwatch.elapsedMilliseconds / imageAssets.length).toStringAsFixed(2)}ms');

      // 计算各阶段占比
      double formDataPercent = (formDataStopwatch.elapsedMilliseconds /
              totalStopwatch.elapsedMilliseconds) *
          100;
      double networkPercent = (networkStopwatch.elapsedMilliseconds /
              totalStopwatch.elapsedMilliseconds) *
          100;
      double parsePercent = (parseStopwatch.elapsedMilliseconds /
              totalStopwatch.elapsedMilliseconds) *
          100;

      print('时间占比分析:');
      print('  - FormData构建: ${formDataPercent.toStringAsFixed(1)}%');
      print('  - 网络上传: ${networkPercent.toStringAsFixed(1)}%');
      print('  - 响应解析: ${parsePercent.toStringAsFixed(1)}%');
      print('========================');

      return result;
    } catch (e) {
      totalStopwatch.stop();
      print('=== 上传失败 ===');
      print('Error: $e');
      print('失败前总耗时: ${totalStopwatch.elapsedMilliseconds}ms');
      print('================');
      throw Exception('上传图片失败: $e');
    }
  }

  // 上传File对象作为图片（用于上传视频缩略图）
  Future<String> uploadImageFile(File imageFile, String fileName,
      {ProgressCallback? onSendProgress}) async {
    try {
      print('=== 开始上传图片文件 ===');
      print('文件路径: ${imageFile.path}');
      print('文件名: $fileName');

      FormData formData = FormData();
      formData.fields.add(MapEntry('type', '5')); // 图片类型为5

      if (await imageFile.exists()) {
        print('✅ 文件存在');
        print('文件大小: ${await imageFile.length()} bytes');

        // 根据文件扩展名确定ContentType
        MediaType? contentType = _getContentType(fileName);
        print('文件类型: $contentType');

        MultipartFile multipartFile = await MultipartFile.fromFile(
          imageFile.path,
          filename: fileName,
          contentType: contentType,
        );

        print('MultipartFile 创建成功');
        formData.files.add(MapEntry('file', multipartFile));
      } else {
        throw Exception('文件不存在: ${imageFile.path}');
      }

      if (formData.files.isEmpty) {
        throw Exception('没有可上传的文件');
      }

      String uri = '/api/v1/bgc/file/upload';
      final response = await _apiClient.post(
        uri,
        data: formData,
        headers: {'Accept': '*/*'},
        onSendProgress: onSendProgress,
      );

      print('=== 图片文件上传响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${response.data}');
      print('========================');

      // 解析响应
      final apiResponse = ApiResponse<String>.fromJson(
        response.data,
        (data) => data as String,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        print('图片文件上传成功，获得URL: ${apiResponse.data}');
        return apiResponse.data!;
      } else {
        throw Exception('图片文件上传失败: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== 图片文件上传失败 ===');
      print('Error: $e');
      print('======================');
      throw Exception('上传图片文件失败: $e');
    }
  }

  // 真实上传单个图片文件 特殊场景
  Future<String> uploadImage(AssetEntity imageAsset,
      {ProgressCallback? onSendProgress}) async {
    try {
      FormData formData = FormData();
      formData.fields.add(MapEntry('type', '5')); // 图片类型为5
      // 为每个文件添加单独的files字段
      final File? file = await imageAsset.file;
      if (file != null) {
        if (await file.exists()) {}

        String fileName = _generateFileName(imageAsset, file);
        // 根据文件扩展名确定ContentType
        MediaType? contentType = _getContentType(fileName);
        MultipartFile multipartFile = await MultipartFile.fromFile(
          file.path,
          filename: fileName,
          contentType: contentType,
        );
        // 每个文件都添加一个独立的files字段（这是关键！）
        formData.files.add(MapEntry('file', multipartFile));
      } else {}
      print('formData$formData');
      if (formData.files.isEmpty) {
        throw Exception('没有可上传的文件');
      }
      // 4. 修正URL路径 - 添加缺失的pacsun/community
      String uri = '/api/v1/bgc/file/upload';
      final response = await _apiClient.post(
        uri,
        data: formData,
        headers: {'Accept': '*/*'},
        onSendProgress: onSendProgress,
      );
      // 5. 解析响应
      final apiResponse = ApiResponse<String>.fromJson(
        response.data,
        (data) => data as String,
      );
      return apiResponse.data ?? '';
    } catch (e) {
      throw Exception('上传图片失败: $e');
    }
  }

  // 生成文件名
  String _generateFileName(AssetEntity asset, File file) {
    // 优先使用 asset.title
    if (asset.title != null && asset.title!.contains('.')) {
      return asset.title!;
    }

    // 其次使用文件路径中的文件名
    String pathFileName = file.path.split('/').last;
    if (pathFileName.contains('.')) {
      return pathFileName;
    }

    // 最后使用默认命名规则
    String extension = asset.type == AssetType.image ? 'jpg' : 'mp4';
    return '${asset.id}.$extension';
  }

  // 解析上传响应
  List<String> _parseUploadResponse(dynamic responseData) {
    final apiResponse = ApiResponse<List<dynamic>>.fromJson(
      responseData,
      (data) => data as List<dynamic>,
    );

    if (apiResponse.isSuccess && apiResponse.data != null) {
      List<String> uploadedUrls = List<String>.from(apiResponse.data!);
      print('上传成功，获得URLs: $uploadedUrls');
      return uploadedUrls;
    } else {
      throw Exception('upload image failed: ${apiResponse.message}');
    }
  }

  // 保留原有的模拟上传方法用于测试
  Future<String> mockUploadMedia(AssetEntity asset) async {
    await Future.delayed(Duration(seconds: 1));
    return 'https://example.com/uploads/${asset.id}.${asset.type == AssetType.image ? 'jpg' : 'mp4'}';
  }

  Future<List<String>> mockUploadMultipleMedia(List<AssetEntity> assets) async {
    List<String> uploadedUrls = [];
    for (AssetEntity asset in assets) {
      String url = await mockUploadMedia(asset);
      uploadedUrls.add(url);
    }
    return uploadedUrls;
  }

  // 根据文件扩展名获取ContentType
  MediaType? _getContentType(String fileName) {
    String extension = fileName.split('.').last.toLowerCase();
    switch (extension) {
      // 图片格式
      case 'jpg':
      case 'jpeg':
        return MediaType('image', 'jpeg');
      case 'png':
        return MediaType('image', 'png');
      case 'gif':
        return MediaType('image', 'gif');
      case 'webp':
        return MediaType('image', 'webp');
      case 'heic':
        return MediaType('image', 'heic');
      // 视频格式
      case 'mp4':
        return MediaType('video', 'mp4');
      case 'mov':
        return MediaType('video', 'quicktime');
      case 'avi':
        return MediaType('video', 'x-msvideo');
      case 'mkv':
        return MediaType('video', 'x-matroska');
      case 'm4v':
        return MediaType('video', 'x-m4v');
      case 'webm':
        return MediaType('video', 'webm');
      default:
        // 根据文件名判断是图片还是视频
        if (fileName.toLowerCase().contains('video') ||
            fileName.toLowerCase().contains('recording') ||
            fileName.toLowerCase().contains('movie')) {
          return MediaType('video', 'mp4'); // 默认视频格式
        }
        return MediaType('image', 'jpeg'); // 默认图片格式
    }
  }

  // 真实上传单个视频文件
  Future<String> uploadVideo(AssetEntity videoAsset,
      {ProgressCallback? onSendProgress}) async {
    try {
      print('=== 开始上传视频 ===');
      print('视频Asset ID: ${videoAsset.id}');
      print('视频Asset Type: ${videoAsset.type}');
      print('视频Asset Title: ${videoAsset.title}');

      FormData formData = FormData();
      formData.fields.add(MapEntry('type', '6')); // 视频类型为6

      final File? file = await videoAsset.file;
      if (file != null) {
        print('✅ 成功获取视频文件');
        print('文件路径: ${file.path}');
        print('文件是否存在: ${await file.exists()}');
        if (await file.exists()) {
          print('文件大小: ${await file.length()} bytes');
        }

        String fileName = _generateFileName(videoAsset, file);
        print('生成的文件名: $fileName');

        // 根据文件扩展名确定ContentType
        MediaType? contentType = _getContentType(fileName);
        print('文件类型: $contentType');

        MultipartFile multipartFile = await MultipartFile.fromFile(
          file.path,
          filename: fileName,
          contentType: contentType,
        );

        print('MultipartFile 创建成功');
        print('MultipartFile 文件名: ${multipartFile.filename}');
        print('MultipartFile 长度: ${multipartFile.length}');

        formData.files.add(MapEntry('file', multipartFile));
      } else {
        throw Exception('无法获取视频文件: asset.file 返回null');
      }

      if (formData.files.isEmpty) {
        throw Exception('没有可上传的视频文件');
      }

      print('FormData 构建完成，开始上传视频...');

      String uri = '/api/v1/bgc/file/upload/video';
      final response = await _apiClient.post(
        uri,
        data: formData,
        headers: {'Accept': '*/*'},
        onSendProgress: onSendProgress,
      );

      print('=== 视频上传响应 ===');
      print('Status Code: ${response.statusCode}');
      print('Response Data: ${response.data}');
      print('===================');

      // 解析响应 - 视频上传返回单个URL字符串
      final apiResponse = ApiResponse<String>.fromJson(
        response.data,
        (data) => data as String,
      );

      if (apiResponse.isSuccess && apiResponse.data != null) {
        print('视频上传成功，获得URL: ${apiResponse.data}');
        return apiResponse.data!;
      } else {
        throw Exception('视频上传失败: ${apiResponse.message}');
      }
    } catch (e) {
      print('=== 视频上传失败 ===');
      print('Error: $e');
      print('==================');
      throw Exception('上传视频失败: $e');
    }
  }

  // 上传视频并提取缩略图，返回视频URL和缩略图URL - 添加时间统计
  Future<Map<String, String>> uploadVideoWithThumbnail(
      AssetEntity videoAsset) async {
    final Stopwatch totalStopwatch = Stopwatch()..start();

    try {
      print('=== 开始上传视频和缩略图 ===');
      print('视频Asset ID: ${videoAsset.id}');
      print('开始时间: ${DateTime.now()}');

      // 1. 提取视频缩略图
      final Stopwatch thumbnailStopwatch = Stopwatch()..start();
      final File? thumbnailFile = await extractVideoThumbnail(videoAsset);
      thumbnailStopwatch.stop();

      if (thumbnailFile == null) {
        throw Exception('视频缩略图提取失败');
      }

      print('缩略图提取完成 (耗时: ${thumbnailStopwatch.elapsedMilliseconds}ms)');

      // 2. 并行上传视频和缩略图
      final Stopwatch uploadStopwatch = Stopwatch()..start();

      print('开始并行上传视频和缩略图...');
      final List<Future> uploadFutures = [
        _uploadVideoWithTiming(videoAsset), // 上传视频
        _uploadImageFileWithTiming(
            thumbnailFile, 'video_thumbnail_${videoAsset.id}.jpg'), // 上传缩略图
      ];

      final List<String> results =
          await Future.wait(uploadFutures.cast<Future<String>>());
      uploadStopwatch.stop();

      final String videoUrl = results[0];
      final String thumbnailUrl = results[1];

      print('并行上传完成 (耗时: ${uploadStopwatch.elapsedMilliseconds}ms)');
      print('=== 视频和缩略图上传完成 ===');
      print('视频URL: $videoUrl');
      print('缩略图URL: $thumbnailUrl');

      // 3. 清理临时缩略图文件
      final Stopwatch cleanupStopwatch = Stopwatch()..start();
      try {
        await thumbnailFile.delete();
        cleanupStopwatch.stop();
        print('临时缩略图文件已清理 (耗时: ${cleanupStopwatch.elapsedMilliseconds}ms)');
      } catch (e) {
        cleanupStopwatch.stop();
        print('清理临时文件失败: $e (耗时: ${cleanupStopwatch.elapsedMilliseconds}ms)');
      }

      totalStopwatch.stop();

      print('=== 视频上传时间统计汇总 ===');
      print('缩略图提取时间: ${thumbnailStopwatch.elapsedMilliseconds}ms');
      print('并行上传时间: ${uploadStopwatch.elapsedMilliseconds}ms');
      print('清理文件时间: ${cleanupStopwatch.elapsedMilliseconds}ms');
      print(
          '总耗时: ${totalStopwatch.elapsedMilliseconds}ms (${(totalStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
      print('============================');

      return {
        'videoUrl': videoUrl,
        'thumbnailUrl': thumbnailUrl,
      };
    } catch (e) {
      totalStopwatch.stop();
      print('=== 视频和缩略图上传失败 ===');
      print('Error: $e');
      print('失败前总耗时: ${totalStopwatch.elapsedMilliseconds}ms');
      print('==============================');
      throw Exception('上传视频和缩略图失败: $e');
    }
  }

  // 带时间统计的视频上传
  Future<String> _uploadVideoWithTiming(AssetEntity videoAsset) async {
    final Stopwatch stopwatch = Stopwatch()..start();
    try {
      String result = await uploadVideo(videoAsset);
      stopwatch.stop();
      print('🎥 视频上传完成 (耗时: ${stopwatch.elapsedMilliseconds}ms)');
      return result;
    } catch (e) {
      stopwatch.stop();
      print('🎥 视频上传失败 (耗时: ${stopwatch.elapsedMilliseconds}ms): $e');
      rethrow;
    }
  }

  // 带时间统计的图片文件上传
  Future<String> _uploadImageFileWithTiming(
      File imageFile, String fileName) async {
    final Stopwatch stopwatch = Stopwatch()..start();
    try {
      String result = await uploadImageFile(imageFile, fileName);
      stopwatch.stop();
      print('🖼️ 缩略图上传完成 (耗时: ${stopwatch.elapsedMilliseconds}ms)');
      return result;
    } catch (e) {
      stopwatch.stop();
      print('🖼️ 缩略图上传失败 (耗时: ${stopwatch.elapsedMilliseconds}ms): $e');
      rethrow;
    }
  }

  // 添加上传图片并生成缩略图的方法
  Future<Map<String, dynamic>> uploadImagesWithThumbnail(
      List<AssetEntity> imageAssets,
      {int batchSize = 2}) async {
    if (imageAssets.isEmpty) return {'imageUrls': [], 'thumbnailUrl': null};

    final Stopwatch totalStopwatch = Stopwatch()..start();

    try {
      print('=== 开始上传图片和生成缩略图 ===');
      print('总图片数量: ${imageAssets.length}');
      print('开始时间: ${DateTime.now()}');

      // 1. 上传所有图片
      final Stopwatch imagesStopwatch = Stopwatch()..start();
      List<String> imageUrls;

      if (imageAssets.length > 2) {
        imageUrls =
            await uploadImagesInBatches(imageAssets, batchSize: batchSize);
      } else {
        imageUrls = await _uploadImagesOriginal(imageAssets);
      }
      imagesStopwatch.stop();
      print('所有图片上传完成 (耗时: ${imagesStopwatch.elapsedMilliseconds}ms)');

      // 2. 上传第一张图片作为缩略图
      final Stopwatch thumbnailStopwatch = Stopwatch()..start();
      String? thumbnailUrl;

      if (imageAssets.isNotEmpty) {
        print('开始上传第一张图片作为缩略图...');
        final firstImage = imageAssets.first;
        final File? firstImageFile = await firstImage.file;

        if (firstImageFile != null && await firstImageFile.exists()) {
          String thumbnailFileName =
              'thumbnail_${DateTime.now().millisecondsSinceEpoch}.jpg';
          thumbnailUrl =
              await uploadImageFile(firstImageFile, thumbnailFileName);
          print('缩略图上传成功: $thumbnailUrl');
        } else {
          print('⚠️ 无法获取第一张图片文件，跳过缩略图上传');
        }
      }
      thumbnailStopwatch.stop();
      print('缩略图上传完成 (耗时: ${thumbnailStopwatch.elapsedMilliseconds}ms)');

      totalStopwatch.stop();

      print('=== 图片和缩略图上传完成 ===');
      print('图片URLs: $imageUrls');
      print('缩略图URL: $thumbnailUrl');
      print(
          '总耗时: ${totalStopwatch.elapsedMilliseconds}ms (${(totalStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
      print('==============================');

      return {
        'imageUrls': imageUrls,
        'thumbnailUrl': thumbnailUrl,
      };
    } catch (e) {
      totalStopwatch.stop();
      print('=== 图片和缩略图上传失败 ===');
      print('Error: $e');
      print('失败前总耗时: ${totalStopwatch.elapsedMilliseconds}ms');
      print('=============================');
      throw Exception('上传图片和缩略图失败: $e');
    }
  }
}
